<template>
  <div class="cuttingBox" ref="cutBox">
    <canvas id="cutBg" ref="cutBg"></canvas>
    <div class="cut-tool" :class="{active : toolActive}" ref="cutTool">
      <div class="cut-hr">
        <div class="hr-1"></div>
        <div class="hr-2"></div>
        <div class="hr-3"></div>
        <div class="hr-4"></div>
      </div>
      <div ref="lt" id="lt" class="tool-item" :class="{active : toolActive}" style="border-top:2px solid white; border-left:2px solid white; left:-2px; top:-2px;"></div>
      <div ref="lb" id="lb" class="tool-item" :class="{active : toolActive}" style="border-bottom:2px solid white; border-left:2px solid white; left:-2px; bottom:-2px;"></div>
      <div ref="rt" id="rt" class="tool-item" :class="{active : toolActive}" style="border-top:2px solid white; border-right:2px solid white; right:-2px; top:-2px;"></div>
      <div ref="rb" id="rb" class="tool-item" :class="{active : toolActive}" style="border-bottom:2px solid white; border-right:2px solid white; right:-2px; bottom:-2px;"></div>
    </div>
  </div>
</template>

<script>
export default {
  props: {
    // 裁剪比例
    cutParams: {
      type: Object,
      default() {
        return {
          cutWidth: 22,
          cutHeight: 32,
          pxX : 259,
          pxY : 377
        };
      }
    },
    // 画布属性
    canvasStyle: {
      type: [DOMRect, Object]
    },
    // 画布原始尺寸 [w,h]
    originSize : {
      type : [Array]
    },

    custom : {
      type: [Boolean],
      default : false
    }
  },
  data() {
    return {
      canvasCutData : {},
      toolActive : false,
    }
  },
  methods: {
    initBox(style) {
      let cutBox = this.$refs.cutBox; // dom操作
      let bgCanvas = this.$refs.cutBg;
      bgCanvas.width = style.width;
      bgCanvas.height = style.height;
      cutBox.style.width = style.width + "px";
      cutBox.style.height = style.height + "px";
      cutBox.style.top = style.top - 46 + "px";
      cutBox.style.left = style.left + "px";
      // cutBox.style.backgroundColor = "red";
      this.initTool();
    },
    // 初始化裁剪工具
    initTool(){
      let params = this.cutParams;
      let style = this.canvasStyle;
      let cutTool = this.$refs.cutTool;
      // 如果是自定义大小
      if( this.custom ){
        params.pxX = style.width;
        params.pxY = style.height;
      }
      let styleRadio = style.width / style.height;
      let paramsRadio = params.pxX / params.pxY;
      // 判断比例
      if(styleRadio < paramsRadio) {
        cutTool.style.width = style.width + 'px';
        cutTool.style.height = style.width / paramsRadio + 'px'
      }else {
        cutTool.style.height = style.height + 'px';
        cutTool.style.width = style.height * paramsRadio + 'px'
      }
      this.onCutCan(cutTool);
      // 初始化
      this.cutCan(cutTool);
    },
    // 截图框事件
    onCutCan(cutTool) {
      let self = this;
      let cutBox = this.$refs.cutBox;
      let cutLeft = '';
      let cutTop = '';
      let { rt, rb, lt, lb } = this.$refs;
      // 获取当前元素和父级的宽高
      let boxWidth = cutBox.offsetWidth;
      let boxHeight = cutBox.offsetHeight;
      let toolWidth = cutTool.offsetWidth;
      let toolHeight = cutTool.offsetHeight;
      // 初始化，使得截图框在中央
      let initLeft = (boxWidth - toolWidth) / 2;
      let initTop = (boxHeight - toolHeight) / 2;
      cutTool.style.left = initLeft + 'px';
      cutTool.style.top = initTop + 'px'
      self.initCutBg(initTop, initLeft, toolWidth, toolHeight);
      // let toolTop = cutTool.offsetTop;
      // let toolLeft = cutTool.offsetLeft;


      // 这里写吐了都，呕。
      // 之前由于截图框的定位采用postion transform(-50%,-50%)的方式居中
      // 真的是没转过弯来，直接在Init的时候js居中就好了，下面的代码就舒适多了

      cutTool.ontouchstart = function(e) {
        e.preventDefault();
        let width = this.offsetWidth;
        let height = this.offsetHeight;
        let disX = e.targetTouches[0].clientX - this.offsetLeft;
        let disY = e.targetTouches[0].clientY - this.offsetTop;
        self.toolActive = true;
        document.ontouchmove = null;
        // 防止手指快速移除范围后无法继续
        document.ontouchmove = function(e) {
          e.preventDefault();
          console.log('parent')
          let newLeft = e.targetTouches[0].clientX - disX;
          let newTop = e.targetTouches[0].clientY - disY;
          // 判断边界
          if(newLeft <= 0){
            newLeft = 0;
          }else if (newLeft >= ( boxWidth - width ) ) {
            newLeft = boxWidth - width;
          } 
          if(newTop <= 0) {
            newTop = 0;
          }else if( newTop >= ( boxHeight - height)) {
            newTop = boxHeight - height;
          }
          cutTop = newTop;
          cutLeft = newLeft;
          self.initCutBg(cutTop, cutLeft, width, height);
          cutTool.style.left = newLeft + 'px';
          cutTool.style.top = newTop + 'px';
        }
         cutTool.ontouchend = function() {
          document.ontouchmove = null;
          document.ontouchend = null;
          self.cutCan(cutTool,cutLeft,cutTop);
          self.toolActive = false;
        }
      }

      console.log('custom11111111111111asdf',this.custom)
      if( this.custom ) {
        onTouch(rt);
        onTouch(lt);
        onTouch(lb);
        onTouch(rb);
        rt.style.display = 'block';
        lt.style.display = 'block';
        lb.style.display = 'block';
      } else {
        onTouch(rb);
        rt.style.display = 'none';
        lt.style.display = 'none';
        lb.style.display = 'none';
      }
      
      // function endTouch(dom){
      //   dom.ontouchstart = null;
      // }

      function onTouch(dom) {
        console.log(dom.id)
        dom.ontouchstart = function(e) {
          e.preventDefault();
          e.stopPropagation();

          let currentWidth = cutTool.offsetWidth;
          let currentHeight = cutTool.offsetHeight;
          let currentLeft = cutTool.offsetLeft;
          let currentTop = cutTool.offsetTop;

          let nowX = e.targetTouches[0].clientX;
          let nowY = e.targetTouches[0].clientY;
          self.toolActive = true;

          document.ontouchmove = function(e) {
            e.preventDefault();
            let disX = e.targetTouches[0].clientX - nowX; 
            let disY = e.targetTouches[0].clientY - nowY;
            if(dom.id === 'rt') {
              let top = currentTop + disY;
              if(top <= 0){
                cutTool.style.top = 0 + 'px';
              }else if (top >= boxHeight){
                cutTool.style.top = boxHeight + 'px';
              }else {
                cutTool.style.top = currentTop + disY + 'px';
                cutTool.style.height =  parseFloat(currentHeight) - disY + "px";
              }
              let width = parseFloat(currentWidth) + disX;
              if(width >= (boxWidth - currentLeft)){
                  width = (boxWidth - currentLeft);
              }
              cutTool.style.width = width + 'px';
            }

            if(dom.id === 'lt') {
              let top = currentTop + disY;
              if(top <= 0){
                cutTool.style.top = 0 + 'px';
              }else if ( top >= boxHeight ){
                cutTool.style.top = boxHeight + 'px';
              }else {
                cutTool.style.top = currentTop + disY + 'px';
                cutTool.style.height = currentHeight - disY + "px";
              }
              let left = parseFloat(currentLeft) + disX;
              if(left <= 0){
                cutTool.style.left = 0 + 'px';
              }else if ( left >= boxWidth ){
                cutTool.style.left = boxWidth + 'px';
              }else {
                cutTool.style.left = currentLeft + disX + 'px';
                cutTool.style.width =  currentWidth - disX + "px";
              }
            }

            if(dom.id === 'lb') {
              let height = parseFloat(currentHeight) + disY;
              if(height >= (boxHeight - currentTop)){
                  height = (boxHeight - currentTop);
              }
              cutTool.style.height = height + 'px';
              let left = parseFloat(currentLeft) + disX;
              if(left <= 0){
                cutTool.style.left = 0 + 'px';
              }else if ( left >= boxWidth ){
                cutTool.style.left = boxWidth + 'px';
              }else {
                cutTool.style.left = currentLeft + disX + 'px';
                cutTool.style.width =  currentWidth - disX + "px";
              }
            }

            if(dom.id === 'rb') {
              let height = parseFloat(currentHeight) + disY;
              if(height >= (boxHeight - currentTop)){
                  height = (boxHeight - currentTop);
              }
              let width = parseFloat(currentWidth) + disX;
              if(width >= (boxWidth - currentLeft)){
                  width = (boxWidth - currentLeft);
              }
              // 按比例缩放
              if( !self.custom ) {
                let paramsRadio = self.cutParams.pxX / self.cutParams.pxY;
                let toolRadio = width / height;
                if(toolRadio >= paramsRadio){
                  height = width / paramsRadio;
                  if(height >= (boxHeight - currentTop)){
                    height = (boxHeight - currentTop);
                    width = height * paramsRadio;
                  }
                }else {
                  width = height * paramsRadio;
                  if(width >= (boxWidth - currentLeft)){
                    width = (boxWidth - currentLeft);
                    height = width / paramsRadio;
                  }
                }
              }
              cutTool.style.height = height + 'px';
              cutTool.style.width = width + 'px';
              
            }

            self.initCutBg(parseFloat(cutTool.style.top), parseFloat(cutTool.style.left) ,parseFloat(cutTool.style.width), parseFloat(cutTool.style.height));
          }

          dom.ontouchend = function() {
            document.ontouchmove = null;
            document.ontouchend = null;
            console.log(cutTool.style.top)
            // self.initCutBg(parseFloat(cutTool.style.top), currentLeft ,parseFloat(cutTool.style.width), parseFloat(cutTool.style.height));
            self.cutCan(cutTool,currentLeft,parseFloat(cutTool.style.top));
            self.toolActive = false;
          }
        }
      }
    },
    cutCan(cutTool, left, top){
      let zoom = this.originSize[0] / this.canvasStyle.width;  // 计算原始图像 / 显示图像 的缩放值
      let originWidth = this.originSize[0];
      let originHeight = this.originSize[1];
      let disWidth = cutTool.offsetWidth;   // 裁剪框大小
      let disHeight = cutTool.offsetHeight;
      let disLeft = left || cutTool.offsetLeft;  // 偏移量
      let disTop = top || cutTool.offsetTop;
      // this.initCutBg(disTop,disLeft,disWidth,disHeight);
      // 计算canvas的相对值
      let canvasLeft = Math.floor(disLeft * zoom);  // 计算相较于canvas left起始值
      let canvasTop = Math.floor(disTop * zoom);
      canvasTop = canvasTop < 0 ? 0 : canvasTop;
      canvasLeft = canvasLeft < 0 ? 0 : canvasLeft;
      let canvasWidth = Math.floor(disWidth * zoom);
      canvasWidth = canvasWidth > originWidth ? originWidth : canvasWidth;
      let canvasHeight = Math.floor(disHeight * zoom);
      canvasHeight = canvasHeight > originHeight ? originHeight : canvasHeight;
      console.log('画布缩放比例:',zoom,'裁剪框偏移量：',disTop,disLeft,'裁剪框大小:',disWidth,disHeight);
      console.log(canvasLeft,canvasTop,canvasWidth,canvasHeight);
      this.canvasCutData = {
        left : canvasLeft, top : canvasTop, width : canvasWidth, height : canvasHeight,
        cutParams : this.cutParams
      }
    },

    initCutBg(top,left,width,height){
      let canvas = this.$refs.cutBg;
      let ctx = canvas.getContext('2d');
      ctx.fillStyle = 'rgba(0,0,0,.5)';
      ctx.clearRect(0,0,canvas.width,canvas.height);
      ctx.fillRect(0,0,canvas.width,canvas.height);
      ctx.clearRect(left,top,width,height);
    }
  },
  mounted() {
    window.cuttingBoxVm = this;
  },
  watch : {
    'canvasStyle' : {
      handler : function(){
        this.initBox(this.canvasStyle);
      }
    },
    'cutParams' : {
      handler : function() {
        this.initTool();
      }
    }
  }
};
</script>

<style scoped>
  .cuttingBox {
    z-index: 0;
  }

  .cut-tool {
    display: inline-block;
    position: absolute;
    /* top: 50%;
    left: 50%;
    transform: translate(-50%, -50%); */
    z-index: 1;
    box-sizing: border-box;
    border: 2px solid rgba(255 , 255, 255, .5);
  }

  .cut-tool.active {
    border-color: rgba(147, 190, 255, 0.5) !important;
  }

  .tool-item.active {
    border-color: rgba(46, 130, 255) !important;
  }

  .cut-tool .cut-hr {
    width: 100%;
    height: 100%;
    position: relative;
  }

  .cut-tool .cut-hr .hr-1 {
    position: absolute;
    width: 100%;
    height: 2px;
    background: rgba(255, 255, 255, 0.5);
    top: 33%;
  }

  .cut-tool .cut-hr .hr-2 {
    position: absolute;
    width: 100%;
    height: 2px;
    background: rgba(255, 255, 255, 0.5);
    top: 66%;
  }

  .cut-tool .cut-hr .hr-3 {
    position: absolute;
    height: 100%;
    width: 2px;
    background: rgba(255, 255, 255, 0.5);
    left: 33%;
  }

  .cut-tool .cut-hr .hr-4 {
    position: absolute;
    height: 100%;
    width: 2px;
    background: rgba(255, 255, 255, 0.5);
    left: 66%;
  }


  .tool-item {
    position:absolute; 
    width:16px; 
    height:16px; 
    overflow:hidden;
    transition: all .2s;
  }


</style>